<template>
  <div class="description-content" :class="[noContent && !isImgTextPreview ? '':'c-pb40', isFullScreen ? 'c-p c-pz1003' : 'c-p c-pz0']">
    <div v-for="(item,index) in descriptList" :key="index">
      <!-- 富文本内容 -->
      <div v-if="item.type == 1" id="descParent" @click="clickDesc" :class="[!isCopyPicture ? 'closeBig' : 'aCloseBig', !isCopy ? 'copyNot' : '']" class="tinymce-text c-wb-ba c-pt20 c-p c-pz1" v-html="item.content"></div>
      <!-- 文字 -->
      <div v-else-if="item.type == 4 && isUseEnableEditor" :class="[!isCopyPicture ? 'closeBig' : 'aCloseBig', !isCopy ? 'copyNot' : '']" class="c-fs26 c-fc-xblack c-lh40 c-pt20 c-wb-ba" v-html="item.content"></div>
      <!-- 图片 -->
      <div v-else-if="item.type == 5 && isUseEnableEditor" id="descImgParent" @click="clickDesc" :class="[!isCopyPicture ? 'closeBig' : 'aCloseBig', !isCopy ? 'copyNot' : '']" class="c-pt20">
        <img class="c-w100" :src="$addXossFilter(item.content)" alt="">
      </div>
      <!-- 音频内容 -->
      <div v-else-if="item.type == 3" class="c-pt20">
        <aplayer @play="playAplayer" preload="auto" mutex="true" :volume="1" repeat="repeat-one" :music="{
          artist:' ',
          title: item.title,
          src: isiOS ? item.audioM3u8 : item.audioM4a,
          pic:require('../../assets/i/wap/clockIn/audio_cover_d.png'),
        }" />
      </div>
      <!-- 视频内容 -->
      <div v-else-if="item.type == 2" class="c-pt20">
        <div :id='"myVideo" + index' class="clock-video pz0 c-w100-im" style="width:100%; height:auto;"></div>
      </div>
      <!-- 关联课程，直播，专栏， 资料， 知识套餐， 电子书 -->
      <div @click="clickDescriptionItem(item)" v-else-if="isUseEnableEditor" class="c-mt20 c-bg-fa c-ph24 c-pv20 c-flex-row c-aligni-stretch br-8px">
        <div class="c-ww192 c-hh130 c-br8 c-flex-row c-flex-center c-text-hidden">
          <img :src="$addXossFilter(item.content)" class="c-maxh c-maxw c-br8" alt="" />
        </div>
        <div class="c-ph20 c-pv4 c-flex-grow1 c-w0 c-flex-column c-justify-sb">
          <div class="c-fs24 c-fc-xblack c-text-ellipsis2">{{item.title}}</div>
          <div class="c-fs24 c-fc-gray">{{DESCTIPTION_TYPE_MAP[item.type]}}</div>
        </div>
      </div>
    </div>
    <loading-status-tem :noData="noContent && !isImgTextPreview" :pt20="true" noDataText="暂无介绍" :class="noContent && !isImgTextPreview ? 'c-pv100' : ''"></loading-status-tem>
  </div>
</template>

<script>
import { wxUtilJs, utilJs } from "@/utils/common.js"
import VueAPlayer from "@/plugin/vue-aplayer/vue-aplayer.vue";
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import { getXgplayer, destoryPlayer } from "@/utils/xgplayerJs.js";
import { goDetails } from "@/utils/goDetails.js";
let previewTimmer = null;
// let tenObjArr = [];
export default {
  name: "CourseDescription",
  components: {
    Aplayer: VueAPlayer,
    loadingStatusTem,
  },
  props: {
    prodType: {
      type: Number,
      default: 5
    },
    prodId: {
      type: Number,
      default: 0
    },
    imgTextPreviewArr: {
      type: Array,
      default: []
    },
    isImgTextPreview:{
      type: Boolean,
      default: false
    },
    independentCopy: { //-1使用全局开关
      type: Number,
      default: -1
    },
    independentCopyPicture: { //-1使用全局开关
      type: Number,
      default: -1
    },
  },
  data() {
    return {
      // isCopy: true,
      // isCopyPicture: true,
      descriptList: [],
      noContent:false,
      DESCTIPTION_TYPE_MAP: {
        '8': '资料',
        '9': '专栏',
        '11': '测评',
        '51': '公开课',
        '61': '知识套餐',
        '78': '训练营',
        '110': '视频',
        '111': '音频',
        '112': '图文',
        '142': '电子书',
      },
      enableNewEditor: localStorage.getItem("enableNewEditor"),
      tenObjArr: [],
      isFullScreen: false
    };
  },
  watch: {
    descriptList: {
      handler: function (newVal, oldVal) {
        this.tenObjArr = [];
        for (let i = 0; i < newVal.length; i++) {
          if (newVal[i].type == 2) {
            this.$nextTick(() => {
              this.initTcPlayer(i, newVal[i].content, newVal[i].videoM3u8, newVal[i].videoCover);
            });
          }
        }
      },
      immediate: true
    },
  },
  computed: {
    isUseEnableEditor() {
      // 详情组件有区分新旧版编辑器，旧版编辑器单独文字、图片、关联课程都不显示, 但是打卡、训练营、电子书没有被新旧编辑器开关限制
      return (this.enableNewEditor && this.enableNewEditor == 1 && ![global.ckFrom.clockIn, global.ckFrom.camp, global.ckFrom.ebooks].includes(this.prodType)) || ([global.ckFrom.clockIn, global.ckFrom.camp, global.ckFrom.ebooks].includes(this.prodType))
    },
    isCopy() {
      let cfg = localStorage.getItem("cfg") && JSON.parse(localStorage.getItem("cfg"));
      return this.independentCopy == -1 ? (cfg && cfg.isCopy == 0 ? false : true) : this.independentCopy;
    },
    isCopyPicture() {
      let cfg = localStorage.getItem("cfg") && JSON.parse(localStorage.getItem("cfg"));
      return this.independentCopyPicture == -1 ? (cfg && cfg.isCopyPicture == 0 ? false : true) : this.independentCopyPicture;
    }
  },
  methods: {
    //详情关联相关
    clickDescriptionItem(item) {
      let courseType = item.type == 110 ? 0 : item.type == 111 ? 1 : item.type == 112 ? 2 : '';
      let prodType = item.type == 110 || item.type == 111 || item.type == 112 ? global.ckFrom.course : item.type;
      goDetails(this, prodType, item.objId, '', courseType)
    },
    initData() {
      // let cfg = localStorage.getItem("cfg") && JSON.parse(localStorage.getItem("cfg"));
      // this.isCopy = this.independentCopy == -1 ? (cfg && cfg.isCopy == 0 ? false : true) : this.independentCopy;
      // this.isCopyPicture = this.independentCopyPicture == -1 ? (cfg && cfg.isCopyPicture == 0 ? false : true) : this.independentCopyPicture;
      this.descriptList = [];
      this.noContent = false;
    },
    getPageHtml(resArr) {
      return new Promise((resolve, reject) => {
        let n = -1;
        for (let i = 0; i < resArr.length; i++) {
          if (resArr[i].type == 1 && resArr[i].content && resArr[i].content.substring(0, 4) == 'http' && resArr[i].content.length > 5) {
            let ic = resArr[i].content;
            resArr[i].content = "";
            utilJs.getPageHtml(ic, sres => {
              // console.log('替换前html: ' + sres);
              sres = this.replaceHref(sres);
              resArr[i].content = sres;
              n = i;
              if (n == resArr.length - 1) {
                resolve(resArr);
              }
            }, () => {
              resArr[i].content = "";
              n = i;
              if (n == resArr.length - 1) {
                resolve(resArr);
              }
            });
          } else {
            n = i;
            if (n == resArr.length - 1) {
              resolve(resArr);
            }
          }
        }
      });
    },
    replaceHref(txt) {
      // 主要用于小程序环境判断详情内容是否有对应的公众号链接，有则统一替换成小程序套壳的链接地址
      let regex = /(<a\s+[^>]*?)(href=["']?)([^"'>]+)(\/?"[^>]*?>)/g;
      txt = txt.replace(regex, function (match, p1, p2, p3, p4) {
        let newHref = p3;
        let companyId = localStorage.getItem('companyId');
        if (
            utilJs.checkWxApp() &&
            ((p3.indexOf('kptest.ckjr001.com/kpv2p') > -1) || (p3.indexOf('wx.ckjr001.com/kpv2p') > -1) || (p3.indexOf('wxapph5.ckjr001.com') > -1)) &&
            ((p3.indexOf('kpv2plive') > -1 ? p3.split('kpv2plive/')[1].split('/?#')[0] : p3.split('kpv2p/')[1].split('/?#')[0]) == companyId)
        ) {
          newHref = `https://wxapph5.ckjr001.com/mini/${p3.indexOf('kpv2plive') > -1 ? p3.split('kpv2plive/')[1] : p3.split('kpv2p/')[1]}`;
        }
        return p1 + p2 + newHref + p4;
      });
      // console.log('替换后html: ' + txt);
      return txt
    },
    // 不通过接口直接获取到descript内容
    getDescriptInfo(resArr) {
      this.initData();
      this.$nextTick(() => {
        if (resArr && resArr.length > 0) {
          this.getPageHtml(resArr).then(res => {
            this.descriptList = res.filter((item) => {
              return item.assetStatus == 1 || item.assetStatus == null;
            });
            if (this.descriptList.length == 1 && this.descriptList[0].type == 1 && (!this.descriptList[0].content)) {
              this.noContent = true;
              this.$emit('checkHasDescription');
            }
          });
        } else {
          this.descriptList = [];
          this.noContent = true;
          this.$emit('checkHasDescription');
        }
      })
    },
    // 图文试看详情
    imgTextPreview() {
      this.initData();
      this.$nextTick(async() => {
        let resArr = this.imgTextPreviewArr;
        if (resArr && resArr.length > 0) {
          await this.getPageHtml(resArr).then(res => {
            this.descriptList = res.filter((item) => {
              return item.assetStatus == 1 || item.assetStatus == null;
            });
            if (this.descriptList.length == 1 && this.descriptList[0].type == 1 && (!this.descriptList[0].content)) {
              this.noContent = true;
              this.$emit('checkHasDescription');
            }
          });
        } else {
          this.descriptList = [];
          this.noContent = true;
          this.$emit('checkHasDescription');
        }
      });
    },
    getDescptionDetail() {
      this.initData();
      this.$nextTick(() => {
        utilJs.getMethod(`${global.apiurl}common/prodDetailInfo?prodType=${this.prodType}&prodId=${this.prodId}`, async res => {
          let resArr = res;
          if (resArr && resArr.length > 0) {
            await this.getPageHtml(resArr).then(res => {
              this.descriptList = res.filter((item) => {
                return item.assetStatus == 1 || item.assetStatus == null;
              });
              if (this.descriptList.length == 1 && this.descriptList[0].type == 1 && (!this.descriptList[0].content)) {
                this.noContent = true;
                this.$emit('checkHasDescription');
                return;
              }
              //新编辑器只添加了新的类型，再切换回就编辑器模式，此时没有旧的类型，要展示暂无介绍
              if (this.descriptList.length >= 1 && !(this.enableNewEditor && this.enableNewEditor == 1)) {
                let oldDesIndex = this.descriptList.findIndex((item) => {
                  return (item.type == 1 || item.type == 2 || item.type == 3)
                })
                if (oldDesIndex == -1) {
                  this.noContent = true;
                  this.$emit('checkHasDescription');
                  return
                }
              }
            });
          } else {
            this.descriptList = [];
            this.noContent = true;
            this.$emit('checkHasDescription');
          }
        })
      });
    },
    clickDesc(e) {
      if (!this.isCopyPicture) {
        return;
      }
      let imgNodeList = document.querySelectorAll('#descParent img, #descImgParent img');
      let imgArr = [];
      for (let item of imgNodeList) {
        item.src && imgArr.push(item.src)
      }
      previewTimmer = setTimeout(() => {
        if (e.target.tagName == 'IMG' && e.target.src) {
          wxUtilJs.previewImage({
            current: e.target.src, // 当前显示图片的http链接
            urls: imgArr // 需要预览的图片http链接列表
          });
        }
      }, 200)
    },
    playAplayer(src) {
      if (typeof src == 'string') {
        let arr = document.getElementsByTagName("video");
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].src != src) {
            arr[i].pause();
          }
        }
      }
    },
    initTcPlayer(index, mp4Url, videoM3u8, poster) {
      if (mp4Url == '' || mp4Url == null) {
        mp4Url = videoM3u8 ? videoM3u8 : '';
      }
      if (videoM3u8 == '' || videoM3u8 == null) {
        videoM3u8 = mp4Url ? mp4Url : '';
      }
      let winW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
      let videoW = winW - winW * 1.2 / 16;
      let videoObj = {
        customWidth: videoW,
        videoMp4: mp4Url,
        videoM3U8: videoM3u8,
        autoplay: false,
        fluid: false,
        isCssFullScreen: true,
        poster: poster || 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/clockIn/video-bg2.png',
        videoInit: -1,
        isFromMicro: true
      }
      let dId = 'myVideo' + index;
      setTimeout(() => {
        this.tenObjArr[index] = getXgplayer(dId, videoObj);
        this.tenObjArr[index].on("play", () => {
          this.playAplayer(this.tenObjArr[index].src);
        });
        this.tenObjArr[index].on("fullscreenchange", () => {
          if (this.tenObjArr[index].isFullscreen()) {
            this.isFullScreen = true;
          } else {
            this.isFullScreen = false;
          }
        });
      }, 10);
    },
  },
  deactivated() {
    for (let i = 0; i < this.tenObjArr.length; i++) {
      destoryPlayer(this.tenObjArr[i]);
      this.tenObjArr[i] = null;
    }
    this.tenObjArr = [];
    this.isFullScreen = false;
    clearTimeout(previewTimmer);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.closeBig >>> p > img,
.closeBig >>> section > img,
.closeBig >>> div > img,
.closeBig >>> img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.aCloseBig >>> p > a > img,
.aCloseBig >>> section > a > img,
.aCloseBig >>> div > a > img {
  pointer-events: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.description-content .aplayer1 {
  margin: 5px 0;
}
.br-8px {
  border-radius: 8px;
}
.pz0 {
  z-index: 0;
}
@font-face{font-family: 'tiktokTemplateFont';src: url('https://kposshzcdn.ckjr001.com/admin/material/24_material_admin/data/public/font/tiktokFont.otf');}
</style>
<style>
.description-content .aplayer-title {
  font-size: 0.7rem !important;
  color: #333 !important;
  font-weight: 400 !important;
}
.description-content .aplayer-pic {
  height: 2.8rem !important;
}
.description-content .aplayer-info1 {
  height: 2.8rem !important;
}
</style>
